import { Button, Form, Input, Select, message, Steps } from "antd";
import { useState } from "react";
import "./index.scss";
import axios from "axios";
import URL from "../../../env.js";

const { Option } = Select;
const RemoteDB = ({ handleCancel3, getLinks, init }) => {
  const [form] = Form.useForm();
   const isLoginEnv =process.env.REACT_APP_LOGIN_STATUS === 'true'
    let token =
    "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI5OGM3OWFiNzViYzc0IiwiZXhwIjoxNzIyMDc5NzE4fQ.aiiGB0Fer3rXXl042llq8llI2c7xRkGkGltZD0EyQxnuaSokW7SjcGxBuK6Mnpazt-MDxcTfsiKwfGUns2P9dw";
  let userId = "98c79ab75bc74";
  if(isLoginEnv) {
token=localStorage.getItem("token")
userId=localStorage.getItem("userId")
  }
  const [loading, setLoading] = useState(false);
  const [loading1, setLoading1] = useState(false);
  const [step, setStep] = useState(0);
  const [options, setOptions] = useState();
  const onFinish = (values) => {
    setLoading1(true);
    axios({
      headers: {
        "Content-Type": "application/json",
        Authorization: token,
      },
      method: "POST",
      url: `${URL}/api/db/connect/getSchema`,
      data: {
        ...values,
        userId,
      },
    })
      .then((res) => {
        setLoading1(false);
        if (res.data.code === 200) {
          setStep(0);
          message.success(res.data.msg);
          handleCancel3();
          getLinks();
          
        } else {
          message.warning(res.data.data || res.data.msg);
        }
      })
      .catch((e) => {
        setLoading1(false);
        console.log(e);
        message.warning(e.response?.data?.data || e.response?.data?.msg);
      });
  };
  const test = async () => {
    try {
      await form.validateFields([
        "databaseType",
        "title",
        "host",
        "port",
        "servername",
        "username",
        "password",
      ]);
      // 表单验证通过，可以继续提交操作
      const allFields = form.getFieldsValue(true);
      setLoading(true);
      axios({
        headers: {
          "Content-Type": "application/json",
          Authorization: token,
        },
        method: "POST",
        url: `${URL}/api/db/connect`,
        data: {
          ...allFields,
          userId,
        },
      })
        .then((res) => {
          setLoading(false);
          setStep(1);
          if (res.data.code === 200) {
            message.success(res.data.msg);
            let data = res.data.data.databaseNames;
            let options = [];
            data.map((v) => {
              options.push({ label: v, value: v });
            });
            console.log(options);
            setOptions(options);
          } else {
            message.warning(res.data.data || res.data.msg);
          }
        })
        .catch((e) => {
          setLoading(false);
          console.log(e);
        });
    } catch (error) {
      // 表单验证未通过，提示错误信息
      message.error("Please fill in all the fields.");
    }
  };
  const hostRegex = /^(localhost|oracle_11g|(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3})$/;
  return (
    <>
      <Steps
        current={step}
        items={[
          {
            title: "测试连接",
          },
          {
            title: "选择数据库",
          },
        ]}
      />
      <Form
        className="remoteDB"
        form={form}
        layout="vertical"
        requiredMark={false}
        onFinish={onFinish}
      >
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          name="databaseType"
          label="数据源类型"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Select placeholder="选择数据库类型" allowClear>
            <Option value="oracle">Oracle</Option>
            <Option value="mysql">Mysql</Option>
          </Select>
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          label="连接名"
          name="title"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="连接名" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          label="主机"
          name="host"
          rules={[
            {
              required: true,
            },
            {
              pattern: hostRegex,
              message: "请输入有效的 IP 地址或 localhost！",
            },
          ]}
        >
          <Input placeholder="连接IP地址" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          name="port"
          label="端口号"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="连接端口号" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          name="servername"
          label="服务名"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="连接服务名" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="连接用户名" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          name="password"
          label="密码"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input placeholder="连接密码" />
        </Form.Item>
        <Form.Item
          className={step === 1 ? "hidden" : ""}
          wrapperCol={{ offset: 10 }}
        >
          <Button loading={loading} type="primary" onClick={test}>
            获取数据库信息
          </Button>
        </Form.Item>
        <Form.Item
          className={step === 0 ? "hidden" : ""}
          name="selectedDB"
          label="selectedDB"
          rules={[
            {
              required: true,
              message: "'selectedDB' is required,please getDBlists first",
            },
          ]}
        >
          <Select
            name="selectedDB"
            label="selectedDB"
            mode="multiple"
            allowClear
            options={options}
            suffixIcon={null}
          ></Select>
        </Form.Item>

        <Form.Item
          className={step === 0 ? "hidden" : ""}
          wrapperCol={{ offset: 16 }}
        >
          <Button onClick={() => setStep(0)} style={{ marginRight: "10px" }}>
            返回
          </Button>
          <Button loading={loading1} type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};
export default RemoteDB;
